﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Ledict.ConditionExtract.Common
{
    public class WebUtil
    {
        const int _timeout = 100 * 1000;

        /// <summary>
        /// 执行HTTP GET请求。
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <param name="charset">编码字符集</param>
        /// <returns>HTTP响应</returns>
        public static T DoGet<T>(string url, IDictionary<string, string> parameters, string charset)
        {
            string content = DoGet(url, parameters, charset);
            if (string.IsNullOrWhiteSpace(content))
            {
                return default(T);
            }

            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(PublicMethod.DeCodeBase64new(65001, content));
        }

        /// <summary>
        /// 执行HTTP GET请求。
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <param name="charset">编码字符集</param>
        /// <returns>HTTP响应</returns>
        public static T DoGetNew<T>(string url, IDictionary<string, string> parameters, string charset)
        {
            string content = DoGet(url, parameters, charset);
            if (string.IsNullOrWhiteSpace(content))
            {
                return default(T);
            }

            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(content);
        }

        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <param name="charset">编码字符集</param>
        /// <param name="timeout">超时时间秒</param>
        /// <returns>HTTP响应</returns>
        public static T DoPost<T>(string url, object parameters, string charset, int timeout = 100)
        {

            string content = DoPost(url, parameters, charset, timeout);

            if (string.IsNullOrWhiteSpace(content))
            {
                return default(T);
            }
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(content);
        }


        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <param name="charset">编码字符集</param>
        /// <param name="timeout">超时时间秒</param>
        /// <returns>HTTP响应</returns>
        public static T DoPost<T>(string url, object parameters, int timeout = 100)
        {

            string content = DoPostNew(url, parameters, timeout);

            if (string.IsNullOrWhiteSpace(content))
            {
                return default(T);
            }
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(content);
        }
        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <param name="charset">编码字符集</param>
        /// <param name="timeout">超时时间秒</param>
        /// <returns>HTTP响应</returns>
        public static string DoPostNew(string url, object parameters, int timeout = 100)
        {
            //HttpWebRequest req = GetWebRequest(url, "POST", timeout);
            //req.ContentType = "application/json;charset=" + charset;

            //byte[] postData = Encoding.GetEncoding(charset).GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(parameters));
            //Stream reqStream = req.GetRequestStream();
            //reqStream.Write(postData, 0, postData.Length);
            //reqStream.Close();

            //HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            //Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            //return GetResponseAsString(rsp, encoding);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Timeout = 10000;//30秒超时
            //request.ContentType = "application/x-www-form-urlencoded";
            request.ContentType = "application/json";
            HttpWebResponse response;
            try
            {
                //byte[] postdatabyte = Encoding.UTF8.GetBytes(parameters.ToString());
                byte[] postdatabyte = Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(parameters));
                request.ContentLength = postdatabyte.Length;
                ///将数据写入URL中
                Stream myRequestStream = request.GetRequestStream();
                myRequestStream.Write(postdatabyte, 0, postdatabyte.Length);
                myRequestStream.Close();
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = (HttpWebResponse)ex.Response;
                Log.ErrorLog("调用接口出错:url" + url + "出错信息：" + ex.Message);
                Log.WriteLog("调用接口出错:url" + url + "出错信息：" + ex.Message);
            }
            //Encoding encoding = Encoding.GetEncoding(response.CharacterSet);
            Encoding encoding = Encoding.GetEncoding("UTF-8");
            return GetResponseAsString(response, encoding);
        }

        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <param name="charset">编码字符集</param>
        /// <param name="timeout">超时时间秒</param>
        /// <returns>HTTP响应</returns>
        public static string DoPost(string url, object parameters, string charset, int timeout = 100)
        {
            HttpWebRequest req = GetWebRequest(url, "POST", timeout);
            req.ContentType = "application/json;charset=" + charset;

            byte[] postData = Encoding.GetEncoding(charset).GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(parameters));
            Stream reqStream = req.GetRequestStream();
            reqStream.Write(postData, 0, postData.Length);
            reqStream.Close();

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            return GetResponseAsString(rsp, encoding);
        }

        /// <summary>
        /// 执行HTTP GET请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <param name="charset">编码字符集</param>
        /// <returns>HTTP响应</returns>
        public static string DoGet(string url, IDictionary<string, string> parameters, string charset)
        {
            if (parameters != null && parameters.Count > 0)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + BuildQuery(parameters, charset);
                }
                else
                {
                    url = url + "?" + BuildQuery(parameters, charset);
                }
            }

            HttpWebRequest req = GetWebRequest(url, "GET");
            req.ContentType = "application/x-www-form-urlencoded;charset=" + charset;

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            return GetResponseAsString(rsp, encoding);
        }

        /// <summary>
        /// 请求对象
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static HttpWebRequest GetWebRequest(string url, string method, int timeout = 100)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.ServicePoint.Expect100Continue = false;
            req.Method = method;
            req.KeepAlive = true;
            req.UserAgent = "Aop4Net";
            req.Timeout = timeout * 1000;
            return req;
        }

        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        public static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            StringBuilder result = new StringBuilder();
            Stream stream = null;
            StreamReader reader = null;

            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);

                // 按字符读取并写入字符串缓冲
                int ch = -1;
                while ((ch = reader.Read()) > -1)
                {
                    // 过滤结束符
                    char c = (char)ch;
                    if (c != '\0')
                    {
                        result.Append(c);
                    }
                }
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }

            return result.ToString();
        }

        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        public static string BuildQuery(IDictionary<string, string> parameters, string charset)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;

            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }

                    postData.Append(name);
                    postData.Append("=");

                    string encodedValue = HttpUtility.UrlEncode(value, Encoding.GetEncoding(charset));

                    postData.Append(encodedValue);
                    hasParam = true;
                }
            }

            return postData.ToString();
        }
    }
}
